import 'dart:async';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart' as my_get;
import 'package:url_launcher/url_launcher.dart';

import '../../../common/api/x_message_assemble_communicate.dart';
import '../../../common/models/baidu_map/location.dart';
import '../../../common/models/im/im_config.dart';
import '../../../common/models/im/im_message.dart';
import '../../../common/models/im/im_msg_body.dart';
import '../../../common/utils/event_bus.dart';
import '../../../common/utils/flutter_mehod_channel_util.dart';
import '../../../common/utils/loading.dart';
import '../../../common/utils/log_util.dart';
import '../../../common/utils/map_utils.dart';
import '../../../common/utils/o2_api_manager.dart';
import '../../../common/utils/o2_file_path_util.dart';
import '../../../common/utils/o2_http_client.dart';
import '../../common/inner_webview/view.dart';
import '../../common/preview_image/index.dart';
import '../../common/process_webview/view.dart';
import '../../common/video_player/index.dart';
// [baidumap81]
// import '../../common/baidu_map/index.dart';
import 'im_chat_message_list/view.dart';

class ImChatMessageTool {
  final _event = EventBus();
  final channel = O2FlutterMethodChannelUtils();
  // 语音播放器
  // FlutterSoundPlayer? playerModule;
  AudioPlayer? _audioPlayer;
  PlayerState _playerState = PlayerState.stopped;
  StreamSubscription? _playerCompleteSubscription;

  // 配置文件
  IMConfigData? _configData;

  // 初始化 在GetxController的  onReady 中调用
  void init() {
    _loadImConfig();
    _initSoundPlayer();
  }

  // 销毁 在GetxController的  onClose 中调用
  void dispose() {
    _disposeSoundPlayer();
  }

  Future<void> _loadImConfig() async {
    _configData = await MessageCommunicationService.to.getImConfig();
  }

  IMConfigData getImConfig() {
    return _configData == null
        ? IMConfigData(enableClearMsg: false, enableRevokeMsg: false)
        : _configData!;
  }

  /// 点击消息
  void clickMsgItem(IMMessage info) {
    var body = info.toBody();
    if (body != null) {
      if ((body.type == IMMessageType.audio.name ||
          body.type == IMMessageType.image.name ||
          body.type == IMMessageType.file.name)) {
        _openVoiceImageOrFileMsg(info);
      } else if (body.type == IMMessageType.process.name) {
        if (body.work != null && body.work?.isNotEmpty == true) {
          if (my_get.GetPlatform.isDesktop) {
            var url = O2ApiManager.instance.getWorkUrlInPC(body.work!);
            if (url == null) {
              return;
            }
            url +=
                '&${O2ApiManager.instance.tokenName}=${O2ApiManager.instance.o2User?.token ?? ''}';
            _launchInWebViewOrVC(url);
          } else {
            ProcessWebviewPage.open(body.work!,
                title: body.title ?? '${body.processName}-无标题');
          }
        }
      } else if (body.type == IMMessageType.location.name) {
        //
        LocationData locationData = LocationData(
            LocationData.locationDataModeShow,
            latitude: body.latitude,
            longitude: body.longitude,
            address: body.address,
            addressDetail: body.addressDetail);
        // [baidumap10]
        MapUtils.showMapListMenu('${body.longitude}', '${body.latitude}');
        // BaiduMapPage.open(locationData);
      } else if (body.type == IMMessageType.messageHistory.name) {
        ImChatMessageListPage.open(body.messageHistoryIds ?? [], info.id!);
      }
    }
  }

  /// 初始化播放器
  _initSoundPlayer() async {
    _audioPlayer = AudioPlayer();
    _playerCompleteSubscription =
        _audioPlayer?.onPlayerComplete.listen((event) {
      _audioPlayer?.stop();
      _playerState = PlayerState.completed;
      _event.emit(EventBus.imSoundMessageStopPlayMsg);
    });
  }

  ///
  /// 销毁播放器
  ///
  _disposeSoundPlayer() async {
    _audioPlayer?.stop();
    _audioPlayer = null;
    _playerCompleteSubscription?.cancel();
    _playerCompleteSubscription = null;
  }

  ///
  /// 播放语音消息 打开图片或文件消息
  Future<void> _openVoiceImageOrFileMsg(IMMessage info) async {
    var body = info.toBody();
    if (body != null) {
      var fileTempPath = body.fileTempPath;
      if (fileTempPath != null && fileTempPath.isNotEmpty) {
        if (body.type == IMMessageType.audio.name) {
          _playVoice(fileTempPath, info);
        } else if (body.type == IMMessageType.file.name ||
            body.type == IMMessageType.image.name) {
          _openFileOrgImage(fileTempPath, body.fileName ?? "Unknown");
        }
      } else if (body.fileId != null) {
        // 如果配置了 onlyOffice 并且开启配置就使用 onlyOffice 打开
        final serviceEnbale = O2ApiManager.instance.onlyOfficeServiceEnable();
        final configEnbale = getImConfig().enableOnlyOfficePreview == true;
        OLogger.d('配置是否开启 onlyOffice : $configEnbale $serviceEnbale');
        if (serviceEnbale &&
            configEnbale &&
            (body.fileExtension?.toLowerCase() == 'pdf' ||
                body.fileExtension?.toLowerCase() == 'docx' ||
                body.fileExtension?.toLowerCase() == 'doc' ||
                body.fileExtension?.toLowerCase() == 'xlsx' ||
                body.fileExtension?.toLowerCase() == 'xls' ||
                body.fileExtension?.toLowerCase() == 'pptx' ||
                body.fileExtension?.toLowerCase() == 'ppt' ||
                body.fileExtension?.toLowerCase() == 'csv' ||
                body.fileExtension?.toLowerCase() == 'txt')) {
                  _openFileWithOnlyOffice(body);
                } else {
                  _downloadAndOpenFile(info, body);
                }
      }
    }
  }

  /// onlyOffice 打开文件
  _openFileWithOnlyOffice(IMMessageBody body) {
    final downloadUrl = MessageCommunicationService.to.getIMMsgDownloadFileUrl(body.fileId!);
    final url =  O2ApiManager.instance.getOnlyOfficePreviewUrl(body.fileName ?? 'Unknown', downloadUrl);
    OLogger.d('打开 onlyOffice 预览： $url');
    if (url != null) {
      InnerWebviewPage.open(url);
    }
  }

  /// 下载并打开文件
  Future<void> _downloadAndOpenFile(IMMessage info, IMMessageBody body) async {
    // 下载
    // 本地存储路径
    var filePath = await O2FilePathUtil.getImFileDownloadLocalPath(
        body.fileId!, body.fileName ?? "Unknown");
    OLogger.d("下载聊天文件： $filePath");
    if (filePath != null) {
      var file = File(filePath);
      if (!file.existsSync()) {
        Loading.show();
        var downloadUrl = MessageCommunicationService.to
            .getIMMsgDownloadFileUrl(body.fileId!);
        Response response =
            await O2HttpClient.instance.downloadFile(downloadUrl, filePath);
        if (response.statusCode != 200) {
          Loading.showError('im_chat_error_preview_file_fail'.tr);
          if (file.existsSync()) {
            // 下载失败 删除文件
            file.delete();
          }
          return;
        }
        Loading.dismiss();
      }
      if (body.type == IMMessageType.audio.name) {
        _playVoice(filePath, info);
      } else if (body.type == IMMessageType.file.name ||
          body.type == IMMessageType.image.name) {
        _openFileOrgImage(filePath, body.fileName ?? "Unknown");
      }
    } else {
      Loading.showError('im_chat_error_preview_file_fail'.tr);
    }
  }

  ///
  /// 播放音频
  ///
  void _playVoice(String filePath, IMMessage info) async {
    var exist = await File(filePath).exists();
    if (exist) {
      if (!(_playerState == PlayerState.stopped ||
          _playerState == PlayerState.completed)) {
        _audioPlayer?.stop();
      }
      _event.emit(EventBus.imSoundMessagePlayMsg, info.id);
      _audioPlayer?.play(DeviceFileSource(filePath));
    }
  }

  ///
  /// 打开图片或文件
  ///
  Future<void> _openFileOrgImage(String filePath, String fileName) async {
    OLogger.d('预览文件： $fileName $filePath');
    if (filePath.isImageFileName) {
      PreviewImagePage.open(filePath, fileName);
    } else if (filePath.isVideoFileName && !my_get.GetPlatform.isDesktop) {
      VideoPlayerPage.openLocalVideo(filePath, title: fileName);
    } else {
      if (my_get.GetPlatform.isDesktop) {
        // 使用本地软件打开文件
        final Uri uri = Uri.file(filePath);
        if (!await launchUrl(uri)) {
          // 无法打开？
          Loading.toast('im_msg_download_success'.tr);
        }
      } else {
        channel.openLocalFile(filePath);
      }
    }
  }

  /// 内部打开链接
  Future<void> _launchInWebViewOrVC(String url) async {
    Uri? uri = Uri.tryParse(url);
    if (uri == null) {
      OLogger.e(' 错误的 url $url ');
      return;
    }
    if (!await launchUrl(
      uri,
      webViewConfiguration: WebViewConfiguration(headers: <String, String>{
        O2ApiManager.instance.tokenName:
            O2ApiManager.instance.o2User?.token ?? ''
      }),
    )) {
      OLogger.e('Could not launch $url');
    }
  }

  /// 外部打开链接
  Future<void> _launchExternal(String url) async {
    Uri? uri = Uri.tryParse(url);
    if (uri != null && await canLaunchUrl(uri)) {
      final result = await launchUrl(
        uri,
        mode: LaunchMode.externalApplication,
        webViewConfiguration: WebViewConfiguration(headers: <String, String>{
          O2ApiManager.instance.tokenName:
              O2ApiManager.instance.o2User?.token ?? ''
        }),
      );
      if (!result) {
        OLogger.e('打开 url $url 失败！');
      }
    } else {
      OLogger.e(' 错误的 url $url ');
    }
  }
}
